package com.jeaven.classpath;

import com.jeaven.classfile.ClassFile;
import com.jeaven.classfile.classreader.ClassReader;

import java.io.IOException;

public class ClassPath {  // 在 classpath 下面找到类
    private static final String[] ApplicationClassPaths;  // 应用程序类的加载路径集合
    private static final String[] BootstrapClassPaths;  // 启动类的加载路径集合

    static {
        ApplicationClassPaths = new String[] { ClassPath.class.getClassLoader().getResource("").getPath() }; // /D:/jeavenwong/SimpleJVM/jvm-core/target/classes/
        BootstrapClassPaths = new String[] { ClassPath.class.getClassLoader().getResource("").getPath() }; // /D:/jeavenwong/SimpleJVM/jvm-core/target/classes/
    }

    public ClassPath() {
        super();
    }

    // BootstrapClassLoader 使用来查找BootstrapClassPath路径下的启动类
    public static ClassFile findClass0(String className) throws IOException {
        String clazzName = className.replace(".","/");
        clazzName = clazzName + ".class";
        for(String BootstrapClassPath : BootstrapClassPaths) {
            ClassFile classFile = ClassReader.read(BootstrapClassPath + clazzName);
            if(classFile != null) {
                return classFile;
            }
        }
        throw new IllegalStateException("unknown class...");
    }

    // ApplicationClassLoader 使用来查找ApplicationClassPath路径下的启动类
    public static ClassFile findClass1(String className) throws IOException {
        String clazzName = className.replace(".","/");
        clazzName = clazzName + ".class";
        for(String ApplicationClassPath : ApplicationClassPaths) {
            ClassFile classFile = ClassReader.read(ApplicationClassPath + clazzName);
            if(classFile != null) {
                return classFile;
            }
        }
        throw new IllegalStateException("unknown class...");
    }

}
